package com.qianniu.napi.common.util;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.English;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.entity.wxbean.LineWord;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.config.Constants;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenxuebin on 2016/11/12.
 */
public class PictureUtil {

    public static final String SIGN_MOTTO = "SIGN_MOTTO" ;
    public static final String SIGN_TIME = "SIGN_TIME" ;
    public static final String SIGN_DATE = "SIGN_DATE" ;
    public static final String SIGN_RANKING = "SIGN_RANKING" ;
    public static final String SIGN_LOGOURL = "SIGN_LOGOURL" ;

    private static Logger logger = LoggerFactory.getLogger(PictureUtil.class);


//    private static void createImage(String fileLocation, BufferedImage image) {
//        try {
//            FileOutputStream fos = new FileOutputStream(fileLocation);
//            BufferedOutputStream bos = new BufferedOutputStream(fos);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
//            encoder.encode(image);
//            bos.close();
//            fos.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void main(String[] args) {

        Font[] arr = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();

        for (Font fon : arr) {
            String name = fon.getFontName();

            if (fon.canDisplay('中') && name.toLowerCase().indexOf("sail") >= 0)
                System.out.println("font name is =" + name);
        }
        System.out.println("font over");

//        if(1==1)return;

        String imgPath = "/Users/chenxuebin/Downloads/tmp_img/tp/20170822/lxl0822_2.jpg" ;

        try {

//            int width =750, height = 375,start =0;
//            boolean byWidth = true;
//            BufferedImage originImage = ImageIO.read(new FileInputStream(imgPath));
//            java.util.List<Color> srcColors = new ArrayList<Color>();
//            srcColors.add(ColorUtil.toColor("#eaeaea"));
//            srcColors.add(ColorUtil.toColor("#ebebeb"));
//            srcColors.add(ColorUtil.toColor("#ececec"));
//            srcColors.add(ColorUtil.toColor("#f1f1f1"));
//            srcColors.add(ColorUtil.toColor("#f0f0f0"));
//            srcColors.add(ColorUtil.toColor("#f2f2f2"));
//            srcColors.add(ColorUtil.toColor("#f3f3f3"));
//            srcColors.add(ColorUtil.toColor("#f4f4f4"));
//            srcColors.add(ColorUtil.toColor("#f5f5f5"));
//            srcColors.add(ColorUtil.toColor("#f6f6f6"));
//            srcColors.add(ColorUtil.toColor("#f7f7f7"));
//            srcColors.add(ColorUtil.toColor("#f8f8f8"));
//            srcColors.add(ColorUtil.toColor("#f9f9f9"));
//            srcColors.add(ColorUtil.toColor("#fafafa"));
//            srcColors.add(ColorUtil.toColor("#fbfbfb"));
//            srcColors.add(ColorUtil.toColor("#fcfcfc"));
//            srcColors.add(ColorUtil.toColor("#fdfdfd"));
//            srcColors.add(ColorUtil.toColor("#fefefe"));
//
//            Color targetColor = ColorUtil.toColor("#ffffff");
//
//            ImageUtil.replaceImageColors(imgPath,imgPath,srcColors,targetColor);
            BufferedImage bis = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D gs = (Graphics2D) bis.getGraphics();
            String FONT_FAMILY = Constants.fontList.get(new Random().nextInt(12));
            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, 26));


            String word = "你无法教会人任何东西，你能做的是帮助他发现一些东西\n" +
                    "----伽利略" ;
            java.util.List<LineWord> alllist = new ArrayList<LineWord>();
            int n = 0;
            String[] words = word.split("\n");
            for (String item : words) {
                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 840, false);
                logger.debug("for word:" + word + ", getSpliteLine list.size =" + list.size());
                alllist.addAll(list);
                n++;
            }


            int width = 840, incrline = 45;
            int height = 100 + alllist.size() * 45 + 80;

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = (Graphics2D) bi.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            String frontColorStr = "6497C7" ;
            TemplateTheme theme = new TemplateTheme("#242424", "#ffffff");

            graphics.setColor(theme.getBgColor());//2b96ac
//            graphics.setColor(new Color(202,235,228));//caebe4
            graphics.fillRect(0, 0, width, height);

            // set front color
            graphics.setColor(theme.getFrontColor());// e9dec3

            int startX = 40;
            int high = 120;
            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 26));
            for (LineWord item : alllist) {
                startX = 420 - item.getWidth() / 2;
                graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            ImageIO.write(bi, "png", new File("/Users/chenxuebin/Downloads/temp/" + FONT_FAMILY + "_" + DateUtil.getTime() + ".png"));

//            String mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU
//                    , Constants.WEIXIN_MATERIAL_IMAGE
//                    , uid, filepath, Constants.WX_EVT_WISDOM);
//
//            WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId,
//                    Constants.WEIXIN_QIANBAIDU);

        } catch (Exception e) {
            logger.error("error happen", e);
        }
    }

    public static String createHaibaoTemplate(String hbimgPath, String qrpath, int newWidth, int x, int y) {
        String filepath = null;
        String FONT_FAMILY = "Microsoft YaHei" ;

        try {
            logger.debug(">>>>>> createHaibaoTemplate start");

            BufferedImage bi = ImageIO.read(new File(hbimgPath));

            BufferedImage qrImage = ImageUtil.scaleImageByWidth(new File(qrpath), newWidth);

            Graphics2D graphics = (Graphics2D) bi.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.drawImage(qrImage, x, y, Color.white, null);

            filepath = Constants.WX_QBD_IMAGEPATH_TEMPLATE + "_" + DateUtil.getToday() + ".png" ;
            File file = new File(filepath);

            ImageIO.write(bi, "png", file);

            return filepath;
        } catch (Exception e) {
            logger.error("createHaibaoTemplate error", e);
        }

        return filepath;
    }

    public static String createNIUTemplate(User user, Boolean isnotify) {
        String filepath = null;
        IRedisService redis = (IRedisService) SpringUtil.getBean("redisServiceImpl");
        try {
            logger.debug(">>>>>> createNIUTemplate start");
            String mpid = user.getMpid().toString();
            String openid = user.getOpenid();
            String logopath = Constants.WX_QBD_ULOGO_QR + openid + ".jpg" ;
//            File logoFile = new File(logopath);
//            if (!logoFile.exists()) HttpUtils.downloadFile(user.getAvatarPic(), logopath);

//            BufferedImage bi = ImageIO.read(new File(logopath));
            BufferedImage bi = ImageUtil.getUrlByBufferedImage(user.getAvatarPic());
            int width = bi.getWidth();
            BufferedImage logo = ImageUtil.convertCircular(bi, false);

            String niulogo = "/fafa/www/images/qnhd/niuniuniu.png" ;

            BufferedImage niuimg = ImageUtil.scaleImageByWidth(new File(niulogo), width / 4);
            niuimg = ImageUtil.convertCircular(niuimg, true);

            Graphics2D graphics = (Graphics2D) logo.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.drawImage(niuimg, width * 3 / 4, width * 3 / 4, niuimg.getWidth(), niuimg.getWidth(), null);

            filepath = Constants.WX_QBD_IMAGEPATH_TEMPLATE + user.getOpenid() + "_niu.png" ;
            File file = new File(filepath);

            ImageIO.write(logo, "png", file);
            logger.debug(">>>>>> createNIUTemplate create file ok=" + filepath + " for userid=" + user.getId());

            try {
                Runtime.getRuntime().exec("chmod 644 " + filepath);
            } catch (IOException e) {
                logger.error(">>>>>> createWisdomTemplate chmod 644 " + filepath + " error", e);
            }

            String rniukey = Constants.WX_NIUNIUNIU + user.getOpenid();

            // 上传到微信素材库 并保存mediaId到redis
            if (redis.get(rniukey) == null) {

                String mediaId = WeixinUtil.uploadTempMaterial(mpid
                        , Constants.WEIXIN_MATERIAL_IMAGE
                        , openid, filepath, Constants.WX_EVT_WISDOM, 1);

                if (!Strings.isNullOrEmpty(mediaId)) {
                    RedisUtils.set(rniukey, mediaId, 1, TimeUnit.DAYS);
                    logger.debug(">>>>>> createWisdomTemplate rniukey=" + rniukey + " mediaId=" + mediaId);
                }

                if (isnotify) WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId, mpid);
            }

            return filepath;
        } catch (Exception e) {
            logger.error("createHaibaoTemplate error", e);
        }

        return filepath;
    }

//    public static String createWisdomTemplate(java.util.List<String> words, String keyword, java.util.List<String> userIds, boolean isNotifyUser) {
//        String filepath = null;
//        String FONT_FAMILY = "Microsoft YaHei";
//
//        try {
//            logger.debug(">>>>>> createWisdomTemplate start");
//            BufferedImage bis = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);
//            Graphics2D gs = (Graphics2D) bis.getGraphics();
//            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, 28));
//
//            java.util.List<String> alllist = new ArrayList<String>();
//            int n = 0;
//            for (String word : words) {
//                if (words.size() > 5 && n >= 6) break;
//                java.util.List<String> list = getSpliteLine(word, gs.getFontMetrics(), 800 - 80, false);
//                logger.debug("for word:" + word + ", getSpliteLine list.size =" + list.size());
//                alllist.addAll(list);
//                n++;
//            }
////            alllist.add("......");
//
//            int width = 800, incrline = 55;
//            int height = 200 + alllist.size() * 55 + 220 + 10 + 55;
//
//            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
//            Graphics2D graphics = (Graphics2D) bi.getGraphics();
//            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//
////            graphics.setColor(Color.white);
////            Color bg_2b96ac = new Color(43,150,172);//2b96ac
////            Color font_e9dec3 = new Color(233,222,195);// e9dec3
////            TemplateTheme theme = new TemplateTheme(ColorUtil.toColor("2b96ac"),ColorUtil.toColor("e9dec3"));
////            TemplateTheme theme = new TemplateTheme(ColorUtil.toColor("f0fdf0"),ColorUtil.toColor("709a7b"));
//            String frontColorStr = "6497C7";
//            TemplateTheme theme = new TemplateTheme(frontColorStr);
//
//            graphics.setColor(theme.getBgColor());//2b96ac
////            graphics.setColor(new Color(202,235,228));//caebe4
//            graphics.fillRect(0, 0, width, height);
//
//            // set front color
//            graphics.setColor(theme.getFrontColor());// e9dec3
//
//            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 34));
//
//            int high = 60;
//            int startX = 40;
//            graphics.drawString("今日干货『 " + keyword + " 』", startX, high);
//            high += 80;
//            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 28));
//            for (String word : alllist) {
//                graphics.drawString(word, startX, high);
//                high += incrline;
//            }
//            high += 20;
//            String moreText = "了解更多关注公众号回复关键字：" + keyword;
////            graphics.drawString(moreText, startX, high);
//
//            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 24));
//            // 添加广告
//            high = height - 170;
//            graphics.drawString("仟伯度，全方位打开你的认知", startX, high);
//            high += incrline;
//            graphics.drawString("请长按下方二维码关注学习", startX, high);
//            for (String uid : userIds) {
//                logger.debug(">>>>>> createWisdomTemplate start create file for user=" + uid);
//                String wisdomKey = Constants.REDIS_KEYTYPE_WISDOM + uid + "_" + DateUtil.getToday();
//                String isWisdomKey = Constants.REDIS_KEYTYPE_IS_WISDOM + uid + "_" + DateUtil.getToday();
//                if (!Constants.checkMap.containsKey(isWisdomKey))
//                    Constants.checkMap.put(isWisdomKey, new AtomicInteger(0));
//
////                String qbdqr = Constants.WX_QBD_IMAGEPATH_QR+uid+".jpg";
////                String qbdqr = Constants.WX_QBD_IMAGEPATH_QR+uid+"_52b3c0.jpg";
//                String qbdqr = Constants.WX_QBD_IMAGEPATH_QR + uid + "_" + frontColorStr + ".jpg";
//                File qrfile = new File(qbdqr);
//                if (!qrfile.exists()) {
//                    logger.debug(">>>>>> logourl not exsit for user=" + uid);
//                    continue;
//                }
//
//                filepath = Constants.WX_QBD_IMAGEPATH_WISDOM + uid + "_" + DateUtil.getToday() + ".png";
//                File file = new File(filepath);
//                // *********$$$$$$$$ reopen $$$$$$$$$$
////                if(file.exists())continue;
//
//                BufferedImage qrImage = ImageUtil.scaleImageByWidth(qrfile, 150);
//                graphics.drawImage(qrImage, width - 190, height - 190, Color.white, null);
//                // ****** 广告结束  ********
//
//                //将BufferedImage变量写入文件中。
//
//                ImageIO.write(bi, "png", file);
//                logger.debug(">>>>>> createWisdomTemplate create file ok=" + filepath + " for user=" + uid);
//                try {
//                    Runtime.getRuntime().exec("chmod 644 " + filepath);
//                } catch (IOException e) {
//                    logger.error(">>>>>> createWisdomTemplate chmod 644 " + filepath + " error", e);
//                }
//
//                // 上传到微信素材库 并保存mediaId到redis
//                if (RedisUtils.isNullOrEmpty(isWisdomKey)
//                        && Constants.checkMap.get(isWisdomKey).compareAndSet(0, 1)) {
//
//                    String mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU
//                            , Constants.WEIXIN_MATERIAL_IMAGE
//                            , uid, filepath, Constants.WX_EVT_WISDOM,1);
//                    if (!Strings.isNullOrEmpty(mediaId)) {
//                        RedisUtils.set(isWisdomKey,Constants.REDIS_ONE, 1, TimeUnit.DAYS);
//                        RedisUtils.set(wisdomKey,mediaId, 1, TimeUnit.DAYS);
//                        logger.debug(">>>>>> createWisdomTemplate wisdomKey=" + wisdomKey + " mediaId=" + mediaId);
//                    } else {
//                        Constants.checkMap.get(isWisdomKey).compareAndSet(1, 0);
//                        logger.debug(">>>>>> createWisdomTemplate failed for mediaId is null at wisdomKey=" + wisdomKey);
//                    }
//                    if (isNotifyUser) {
//                        WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId,
//                                Constants.WEIXIN_QIANBAIDU);
//                    }
//                }
//
//            }
//            graphics.dispose();
//            logger.debug(">>>>>> createWisdomTemplate over");
//        } catch (Exception e) {
//            logger.error(">>>>>> createWisdomTemplate error ", e);
//        }
//        return filepath;
//    }

//    // 生成个人打卡图
//    // 定时任务生成每日打卡图模板
//    // 打卡时间和排名在4：00--10：00点之间用户第一次来到公众号时触发
//    // 返回 mediaId
//    public static String createSigninTemplate(Map map, String uid, boolean isOnlyTemplate,String wxType) {
//
//        logger.debug(">>>>>> createSignin start ======map=" + JSON.toJSONString(map));
//        if (map==null||(!isOnlyTemplate && !map.containsKey(PictureUtil.SIGN_TIME))) {
//            logger.error("createSigninTemplate parameter map error ");
//            return null;
//        }
//        String FONT_FAMILY = "Microsoft YaHei";
//
//        String result = Constants.WX_QBD_IMAGEPATH_SIGNIN + uid + "_" + DateUtil.getToday() + ".png";
//        String mediaId = null;
//
//        logger.debug(">>>>>> createSignin start1.2 ======");
//
//        String isSigninKey = Constants.REDIS_KEYTYPE_IS_SIGNIN + uid + "_" + DateUtil.getToday();
//        String signinKey = Constants.REDIS_KEYTYPE_SIGNIN + uid + "_" + DateUtil.getToday();
//        if (!Constants.checkMap.containsKey(isSigninKey)) Constants.checkMap.put(isSigninKey, new AtomicInteger(0));
//
//        logger.debug(">>>>>> createSignin start1.3 ======");
//
//        if (new File(result).exists()) {
//            mediaId = RedisUtils.get(signinKey);
//            if (Strings.isNullOrEmpty(mediaId)
//                    && Constants.checkMap.get(isSigninKey).compareAndSet(0, 1)) {
//
//                mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU,
//                        Constants.WEIXIN_MATERIAL_IMAGE
//                        , uid, result, Constants.WX_EVT_SIGNIN,1);
//
//                if (!Strings.isNullOrEmpty(mediaId)) {
//                    RedisUtils.set(isSigninKey,Constants.REDIS_ONE, 1, TimeUnit.DAYS);
//                    RedisUtils.set(signinKey,mediaId, 1, TimeUnit.DAYS);
//                    if (!isOnlyTemplate)
//                        AkkaServer.system.actorOf(Props.create(NotifyActor.class))
//                                .tell(Constants.WEIXIN_MATERIAL_IMAGE + "@" + uid + "@" + mediaId+ "@" + wxType, ActorRef.noSender());
//
//                } else {
//                    Constants.checkMap.get(isSigninKey).compareAndSet(1, 0);
//                }
//                return mediaId;
//            }
//        }
//
//        logger.debug(">>>>>> createSignin start2 and result=" + result);
//
//        // 打卡图的mediaId对应的key
////        String bgImgPath = Constants.WX_QBD_IMAGEPATH_TEMPLATE+"gap_glass_floor.jpg";// 背景模板
//
//        EnglishDO english = WeixinUtil.randomEnglish();
//
//        String bgImgPath = "/fafa/www" + english.getPath();// 背景模板
//
//        String signTempPath = Constants.WX_QBD_IMAGEPATH_TEMP + "signin_" + uid + "_" + DateUtil.getToday() + ".png";
//        String qrpath = Constants.WX_QBD_IMAGEPATH_QR + uid + "_52B3C0.jpg";
//        boolean hasTemplate = false;
//
//        try {
//            logger.debug(">>>>>> createSignin start3 ======");
//
//            int width = 750, height = 375, start = 0;
//            boolean byWidth = true;
//            File signTempFile = new File(signTempPath);
//
//            if (isOnlyTemplate) {
//
//                if (signTempFile.exists()) {
//                    logger.debug(">>>>>> createSignin signTempFile.exists");
//                    return null;
//                }
//            } else {
//                if (signTempFile.exists()) {
//                    bgImgPath = signTempPath;
//                    hasTemplate = true;
//                }
//            }
//
//            BufferedImage originImage = ImageIO.read(new FileInputStream(bgImgPath));
//            BufferedImage logourl = ImageUtil.getUrlByBufferedImage(RedisUtils.get(Constants.REDIS_USER_LOGO + uid));
//
//            if (originImage.getWidth() / originImage.getHeight() > width / height) {
//                byWidth = false;
//            }
//
//            logger.debug(">>>>>> createSignin start4 ======");
//
//            BufferedImage scaleImage = byWidth ? ImageUtil.scaleImageByWidth(new File(bgImgPath), width) :
//                    ImageUtil.scaleImageByHeight(new File(bgImgPath), height);
//
//            //首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。
////            BufferedImage bimg = new BufferedImage(width, width, BufferedImage.TYPE_3BYTE_BGR);
//            BufferedImage bimg = new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);
//            Graphics2D graphics = (Graphics2D) bimg.getGraphics();
//            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//
////            graphics.drawImage(scaleImage, 0, 0, color,null);
//            graphics.drawImage(scaleImage, 0, 0, null);
//
//            Color white = new Color(255, 255, 255);
//            Color fontcolor = new Color(82, 179, 192);
//            Color bgcolora = new Color(251, 255, 242, 220);
//            Color bggreen = new Color(150, 215, 160, 220);
//            graphics.setColor(white);
//            logger.debug(">>>>>> createSignin start5 ======");
//
//            if (!hasTemplate) {
//                graphics.fillRect(start, height, width, width - height);
//
//                // fill logo background
//                graphics.setColor(bgcolora);
////            graphics.setColor(bggreen);
////                graphics.fillRoundRect(65, 300, width - 130, 170, 10, 10);
//                graphics.fillRoundRect(65, 300, width - 130, 170, 10, 10);
//
//                //  logo
//                BufferedImage cirlebi = ImageUtil.convertCircular(ImageUtil.scaleByPercentage(logourl, 120, 120));
////                graphics.drawImage(cirlebi, 130, 330, null);
////                graphics.drawImage(cirlebi, 100, 330, null);
//                graphics.drawImage(cirlebi, 97, 330, null);
//                logger.debug(">>>>>> createSignin start6 ======");
//            }
//
////            graphics.drawRoundRect(width/2,height/2-50,50,50,90,90);
//            graphics.setColor(fontcolor);
//            // 打开时间
//            if (!isOnlyTemplate) {
//
//                graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 48));
//
//                // 签到时间
////            String time = "07:18";
////                graphics.drawString(map.get(PictureUtil.SIGN_TIME).toString(), 280, 360);
////                graphics.drawString(map.get(PictureUtil.SIGN_TIME).toString(), 250, 360);
//                graphics.drawString(map.get(PictureUtil.SIGN_TIME).toString(), 245, 360);
//
//                // 签到年月
//                graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 24));
////            String year = "2017-07-23";
////                graphics.drawString(map.get(PictureUtil.SIGN_DATE).toString(), 460, 360);
//                graphics.drawString(map.get(PictureUtil.SIGN_DATE).toString(), 455, 360);
//
//                // 打卡排名
//                graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 24));
////            String paiming = "连续打开第1天   好友排名第一";
////                graphics.drawString(map.get(PictureUtil.SIGN_RANKING).toString(), 250, 420);
//                graphics.drawString(map.get(PictureUtil.SIGN_RANKING).toString(), 245, 420);
//
//            }
//
//            if (!hasTemplate) {
//
//                logger.debug(">>>>>> createSignin start8 start======");
//
//                // 二维码
//                BufferedImage cxbbi = ImageUtil.scaleByPercentage(ImageIO.read(new FileInputStream(qrpath)), 120, 120);
////                graphics.drawImage(cxbbi, 580, 560, null);
////                graphics.drawImage(cxbbi, 583, 565, null);
//                graphics.drawImage(cxbbi, 613, 613, null);
//
//                // 二维码说明
//                graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 16));
//                String qrnote = "扫码与好友互道早安";
////                graphics.drawString(qrnote, 585, 720);
//
//                // 鸡汤
//                int startX = 60, startY = 520, incr = 50;
//                graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 26));
//                String motto = map.get(PictureUtil.SIGN_MOTTO).toString();
//                logger.debug(">>>>>> motto=" + motto);
//                java.util.List<String> list = new ArrayList<String>();
//                if (motto.length() <= 20) {
//                    list.add(motto);
//                    startX = 75;
//                    startY = 580;
//                } else {
//                    list = getSpliteLineBysymbol(map.get(PictureUtil.SIGN_MOTTO).toString(), graphics.getFontMetrics(), 540, false);
//                }
//                if (list == null || list.size() >= 6) {
//                    list = getSpliteLine(map.get(PictureUtil.SIGN_MOTTO).toString(), graphics.getFontMetrics(), 540, false);
//                    startY = 520;
//                    incr = 45;
//                    if (list.size() >= 6) startY = 506;
//                }
//                for (int i = 0; i < list.size(); i++) {
//                    if (i > 7) break;
//                    graphics.drawString(list.get(i), startX, startY);
//                    startY += incr;
//                }
//                logger.debug(">>>>>> createSignin start8 end======");
//            }
//
//            if (isOnlyTemplate) result = signTempPath;
//            logger.debug(">>>>>> createSignin to write image result=" + result);
//            ImageIO.write(bimg, "png", new File(result));
//            try {
//                Runtime.getRuntime().exec("chmod 644 " + result);
//            } catch (IOException e) {
//                logger.error("chmod 644 " + result + " error", e);
//            }
//            graphics.dispose();
//
//            if (!isOnlyTemplate && RedisUtils.isNullOrEmpty(isSigninKey)
//                    && Constants.checkMap.get(isSigninKey).compareAndSet(0, 1)) {
//
//                logger.debug(">>>>>> signin resultpath =" + result);
//                mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU,
//                        Constants.WEIXIN_MATERIAL_IMAGE
//                        , uid, result, Constants.WX_EVT_SIGNIN,1);
//                RedisUtils.set(isSigninKey,Constants.REDIS_ONE, 1, TimeUnit.DAYS);
//                RedisUtils.set(signinKey,mediaId, 1, TimeUnit.DAYS);
//
//                logger.debug(">>>>>> createSignin setRedis signinKey=" + signinKey + " mediaId=" + mediaId);
//
//                AkkaServer.system.actorOf(Props.create(NotifyActor.class)).tell(Constants.WEIXIN_MATERIAL_IMAGE + "@" + uid + "@" + mediaId, ActorRef.noSender());
//            }
//            logger.debug(">>>>>> createSignin over ===");
//
//        } catch (Exception e) {
//            logger.error(">>>>>> createSignin error", e);
//        }
//        return mediaId;
//    }


    public static void createPYQTemplate(String uid, String word) {

//            String FONT_FAMILY = Constants.fontList.get(new Random().nextInt(12));
        String FONT_FAMILY = Constants.fontList.get(4);

        try {
            BufferedImage bis = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D gs = (Graphics2D) bis.getGraphics();
            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, 32));

            java.util.List<LineWord> alllist = new ArrayList<LineWord>();
            int n = 0;
            String[] words = word.split("\n");
            for (String item : words) {
                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 780, false);
                alllist.addAll(list);
                n++;
            }

            int width = 780, incrline = 45;
            int height = 60 + alllist.size() * incrline + 40;

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = (Graphics2D) bi.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            TemplateTheme theme = new TemplateTheme("#242424", "#ffffff");

            graphics.setColor(theme.getBgColor());//2b96ac
            graphics.fillRect(0, 0, width, height);

            // set front color
            graphics.setColor(theme.getFrontColor());// e9dec3

            int startX = 40;
            int high = 70;
            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 32));
            for (LineWord item : alllist) {
                startX = 390 - item.getWidth() / 2;
                graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            String filepath = Constants.WX_QBD_IMAGEPATH_PYQ + DateUtil.getTime() + ".png" ;
            File file = new File(filepath);
            ImageIO.write(bi, "png", file);

            String mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU
                    , Constants.WEIXIN_MATERIAL_IMAGE
                    , uid, filepath, Constants.WX_EVT_WISDOM, 1);

            WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId, Constants.WEIXIN_QIANBAIDU);

//            file.deleteOnExit();

        } catch (Exception e) {
            logger.error("error happen", e);
        }
    }
//
//    public static void createPYQPTTemplate(String uid, String word) {
//
////            String FONT_FAMILY = Constants.fontList.get(new Random().nextInt(12));
//        Random rm = new Random();
//        String FONT_FAMILY = Constants.fontList.get(rm.nextInt(8));
//
//        EnglishDO english = WeixinUtil.randomEnglish();
//
//        String bgImgPath = "/fafa/www" + english.getPath();// 背景模板
//        logger.debug(">>>bgImgPath=" + bgImgPath);
//        try {
//
//            int width = 600, height = 300, start = 0;
//            boolean byWidth = true;
//
//            BufferedImage originImage = ImageIO.read(new FileInputStream(bgImgPath));
//            if (originImage.getWidth() / originImage.getHeight() > width / height) {
//                byWidth = false;
//            }
//
//            BufferedImage scaleImage = originImage.getWidth() > 600 ? (
//                    byWidth ? ImageUtil.scaleImageByWidth(new File(bgImgPath), width) :
//                            ImageUtil.scaleImageByHeight(new File(bgImgPath), height)) : originImage;
//
//            logger.debug("scaleImage width=" + scaleImage.getWidth() + " height=" + scaleImage.getHeight());
//
//            //首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。
////            BufferedImage bimg = new BufferedImage(width, width, BufferedImage.TYPE_3BYTE_BGR);
//            BufferedImage bimg = new BufferedImage(10, 10, BufferedImage.TYPE_4BYTE_ABGR);
//            Graphics2D gs = (Graphics2D) bimg.getGraphics();
//
//            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, 23));
//
//            java.util.List<LineWord> alllist = new ArrayList<LineWord>();
//            int n = 0;
//            String[] words = word.split("\n");
//            for (String item : words) {
//                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), width - 30, false);
//                if (list == null) alllist.add(new LineWord());
//                else alllist.addAll(list);
//                n++;
//            }
//
//            int incrline = 40;
//            int new_height = scaleImage.getHeight() + alllist.size() * 40 + 40;
//            if (new_height < 600) new_height = 600;
//
//            BufferedImage bi = new BufferedImage(width, new_height, BufferedImage.TYPE_4BYTE_ABGR);
//            Graphics2D graphics = (Graphics2D) bi.getGraphics();
//            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//
//            TemplateTheme theme = new TemplateTheme("#000000", "#ffffff");
//
//            // fill bgColor
//            graphics.setColor(theme.getFrontColor());//2b96ac
//            graphics.fillRect(0, 0, width, new_height);
//
//            // fill bgimage
//            int pw = 0, ph = 0;
//            if (scaleImage.getWidth() < 600) {
//                pw = (600 - scaleImage.getWidth()) / 2;
//                ph = 20;
//            }
//            graphics.drawImage(scaleImage, pw, ph, null);
//
//            // set front color
//            graphics.setColor(theme.getBgColor());// e9dec3
//
//            int startX = 40;
//            int high = (new_height - scaleImage.getHeight() - alllist.size() * 40) / 2 + scaleImage.getHeight() + 20;
//
//            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, 23));
//            for (LineWord item : alllist) {
//                startX = 300 - item.getWidth() / 2;
////                startX = 30;
//                if (!Strings.isNullOrEmpty(item.getWord())) graphics.drawString(item.getWord(), startX, high);
//                high += incrline;
//            }
//
//            String filepath = Constants.WX_QBD_IMAGEPATH_PYQ + DateUtil.getTime() + ".png";
//            File file = new File(filepath);
//            ImageIO.write(bi, "png", file);
//
//            String mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU
//                    , Constants.WEIXIN_MATERIAL_IMAGE
//                    , uid, filepath, Constants.WX_EVT_WISDOM,1);
//
//            WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId,
//                    Constants.WEIXIN_QIANBAIDU);
//
//            logger.debug(">>>mediaId=" + mediaId);
//
//            file.delete();
//
//        } catch (Exception e) {
//            logger.error("error happen", e);
//        }
//    }

    public static void createQNBTemplate(String uid, String mpid, String word) {

//            String FONT_FAMILY = Constants.fontList.get(new Random().nextInt(12));
//        String FONT_FAMILY = Constants.fontList.get(0);
//        String FONT_FAMILY = Constants.fontList.get(1);
//        String FONT_FAMILY = Constants.fontList.get(2);// 正楷、mlgkt
        String FONT_FAMILY = Constants.fontList.get(6);// 正楷|南宋书局体

        try {
            BufferedImage bis = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D gs = (Graphics2D) bis.getGraphics();
            int fsize = 40;
            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, fsize));

            java.util.List<LineWord> alllist = new ArrayList<LineWord>();
            java.util.List<LineWord> alllist2 = new ArrayList<LineWord>();
            int n = 0;
            String[] words = word.split("##");
            String[] words1 = words[0].split("\n");

            for (String item : words1) {
                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 780, false);
                alllist.addAll(list);
                n++;
            }
            if (words.length > 1) {
                String[] words2 = words[1].split("\n");
                for (String item : words2) {
                    java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 780, false);
                    alllist2.addAll(list);
                    n++;
                }
            }
            if(n>6){
                n = 0;
                fsize = 36;
                gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, fsize));
                for (String item : words1) {
                    java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 780, false);
                    alllist.addAll(list);
                    n++;
                }
                if (words.length > 1) {
                    String[] words2 = words[1].split("\n");
                    for (String item : words2) {
                        java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 780, false);
                        alllist2.addAll(list);
                        n++;
                    }
                }
            }

            int width = 780, incrline = gs.getFontMetrics().getHeight()+8;
            int height = 90 + n * incrline + 160 ;

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = (Graphics2D) bi.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

//            TemplateTheme theme = new TemplateTheme("#242424", "#ffffff");
//            TemplateTheme theme2 = new TemplateTheme("#242424", "#a70c17");
//            TemplateTheme theme2 = new TemplateTheme("#242424", "#dfd831");

            TemplateTheme theme = new TemplateTheme("#242424", "#ffffff");
            TemplateTheme theme2 = new TemplateTheme("#242424", "#dfd831");
            TemplateTheme theme3 = new TemplateTheme("#242424", "#a70c17");

            graphics.setColor(theme.getBgColor());//2b96ac
            graphics.fillRect(0, 0, width, height);

            // set front color
            graphics.setColor(theme.getFrontColor());// e9dec3

            int startX = 40;
            int high = 90;
            graphics.setFont(new Font(FONT_FAMILY, Font.BOLD, fsize));
            for (LineWord item : alllist) {
                logger.debug("=============item="+ JSON.toJSONString(item));
                startX = 390 - item.getWidth() / 2;
                graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            graphics.setColor(theme2.getFrontColor());// e9dec3
            graphics.setFont(new Font(FONT_FAMILY, Font.BOLD, 40));
            for (LineWord item : alllist2) {
                logger.debug("=============item="+ JSON.toJSONString(item));
                startX = 390 - item.getWidth() / 2;
                graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            //qianniu_quan24.jpg
            String niulogo = "/fafa/www/images/qnhd/qianniu50.png" ;
            startX = 390 - 50 / 2 - 150 / 2 - 10;
//            BufferedImage niuimg = ImageIO.read(new FileInputStream(niulogo));
            BufferedImage niuimg = ImageUtil.scaleImageByWidth(new File(niulogo),35);
            graphics.drawImage(niuimg, startX+24, high-10, null);
            startX = 390 - 180 / 2;
//            FONT_FAMILY = Constants.fontList.get(7);
            graphics.setColor(theme3.getFrontColor());// e9dec3
            graphics.setFont(new Font(FONT_FAMILY, Font.BOLD, 32));
            graphics.drawString("仟牛邦", startX+50, high+20);


            String filepath = Constants.WX_QBD_IMAGEPATH_PYQ + DateUtil.getTime() + ".png" ;
            File file = new File(filepath);
            ImageIO.write(bi, "png", file);

            String mediaId = WeixinUtil.uploadTempMaterial(mpid, Constants.WEIXIN_MATERIAL_IMAGE
                    , uid, filepath, Constants.WX_EVT_WISDOM, 1);

            WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId, mpid);
            file.delete();

        } catch (Exception e) {
            logger.error("error happen", e);
        }
    }

    public static void createQNBPTTemplate(String openid, String mpid, String word) {

//            String FONT_FAMILY = Constants.fontList.get(new Random().nextInt(12));
        String FONT_FAMILY = Constants.fontList.get(5);
        English english = WeixinUtil.randomEnglish();
        String bgImgPath = english.getPath().replace("https://img.niucaiduo.com","/fafa/www/images");// 背景模板
        logger.debug(">>>bgImgPath=" + bgImgPath);
        int fsize = 28;
        TemplateTheme theme3 = new TemplateTheme("#242424", "#a70c17");

        try {
            int width = 600, height = 300, start = 0;
            boolean byWidth = true;

            BufferedImage originImage = ImageIO.read(new FileInputStream(bgImgPath));
            if (originImage.getWidth() / originImage.getHeight() > width / height) {
                byWidth = false;
            }

            BufferedImage scaleImage = originImage.getWidth() > 600 ? (
                    byWidth ? ImageUtil.scaleImageByWidth(new File(bgImgPath), width) :
                            ImageUtil.scaleImageByHeight(new File(bgImgPath), height)) : originImage;

            logger.debug("scaleImage width=" + scaleImage.getWidth() + " height=" + scaleImage.getHeight());
            BufferedImage bimg = new BufferedImage(10, 10, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D gs = (Graphics2D) bimg.getGraphics();

            gs.setFont(new Font(FONT_FAMILY, Font.PLAIN, fsize));

            int n = 0;
            java.util.List<LineWord> alllist = new ArrayList<LineWord>();
            java.util.List<LineWord> alllist2 = new ArrayList<LineWord>();
            String[] words = word.split("##");
            String[] words1 = words[0].split("\n");
//            String[] words = word.split("\n");
//            for (String item : words) {
//                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), width - 30, false);
//                if (list == null) alllist.add(new LineWord());
//                else alllist.addAll(list);
//                n++;
//            }

            for (String item : words1) {
                java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 600, false);
                alllist.addAll(list);
                n+=list.size();
            }
            if (words.length > 1) {
                String[] words2 = words[1].split("\n");
                for (String item : words2) {
                    java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 600, false);
                    alllist2.addAll(list);
                    n+=list.size();
                }
            }

            int incrline = gs.getFontMetrics().getHeight()+8;
            int new_height = scaleImage.getHeight() + n * incrline + 140;
            logger.debug("--------------------------------------===========createQNBPTTemplate scaleImage.getHeight()="+scaleImage.getHeight());
            logger.debug("--------------------------------------===========createQNBPTTemplate n="+n);
            logger.debug("--------------------------------------===========createQNBPTTemplate incrline="+incrline);
            logger.debug("--------------------------------------===========createQNBPTTemplate new_height="+new_height);
            if (new_height < 600) new_height = 600;

            BufferedImage bi = new BufferedImage(width, new_height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = (Graphics2D) bi.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            TemplateTheme theme = new TemplateTheme("#000000", "#ffffff");

            // fill bgColor
            graphics.setColor(theme.getFrontColor());//2b96ac
            graphics.fillRect(0, 0, width, new_height);

            // fill bgimage
            int pw = 0, ph = 0;
            if (scaleImage.getWidth() < 600) {
                pw = (600 - scaleImage.getWidth()) / 2;
                ph = 20;
            }
            graphics.drawImage(scaleImage, pw, ph, null);

            // set front color
            graphics.setColor(theme.getBgColor());// e9dec3

            int startX = 40;
            int high = (new_height - scaleImage.getHeight() - n * incrline) / 2 + scaleImage.getHeight() + 20;

            graphics.setFont(new Font(FONT_FAMILY, Font.PLAIN, fsize));
            for (LineWord item : alllist) {
                startX = 300 - item.getWidth() / 2;
//                startX = 30;
                if (!Strings.isNullOrEmpty(item.getWord())) graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            graphics.setColor(theme3.getFrontColor());// e9dec3
            for (LineWord item : alllist2) {
                logger.debug("=============item="+ JSON.toJSONString(item));
                startX = 300 - item.getWidth() / 2;
                if (!Strings.isNullOrEmpty(item.getWord())) graphics.drawString(item.getWord(), startX, high);
                high += incrline;
            }

            //qianniu_quan24.jpg
            String niulogo = "/fafa/www/images/qnhd/qianniu50.png" ;
            startX = 300 - 50 / 2 - 150 / 2 - 10;
//            BufferedImage niuimg = ImageIO.read(new FileInputStream(niulogo));
            BufferedImage niuimg = ImageUtil.scaleImageByWidth(new File(niulogo),30);
            graphics.drawImage(niuimg, startX+48, high+2, null);

            startX = 300 - 180 / 2;
//            FONT_FAMILY = Constants.fontList.get(7);
            graphics.setColor(theme3.getFrontColor());// e9dec3
            graphics.setFont(new Font(FONT_FAMILY, Font.BOLD, 22));
            graphics.drawString("仟牛邦", startX+65, high+25);

            String filepath = Constants.WX_QBD_IMAGEPATH_PYQ + DateUtil.getTime() + ".png";
            File file = new File(filepath);
            ImageIO.write(bi, "png", file);

            String mediaId = WeixinUtil.uploadTempMaterial(mpid, Constants.WEIXIN_MATERIAL_IMAGE
                    , openid, filepath, Constants.WX_EVT_QNB, 1);
            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId, mpid);
            file.delete();


        } catch (Exception e) {
            logger.error("error happen", e);
        }
    }

    public static String createZhufuTemplate(String uid, String word, int findex, int order, boolean isTemplate) {

        Random rm = new Random();
        String FONT_FAMILY = Constants.fontList.get(findex);


        String bgImgPath = "/fafa/www/images/template/yuanmeng_qianniu_haibao.jpg" ;// 背景模板
//        String bgImgPath = "/Users/chenxuebin/Downloads/tmp_img/yuanmeng_qianniu_haibao.jpg";// 背景模板
        logger.debug(">>>bgImgPath=" + bgImgPath);
        try {

            boolean byWidth = true;

            BufferedImage originImage = ImageIO.read(new FileInputStream(bgImgPath));
            int width = originImage.getWidth(), height = originImage.getHeight(), start = 0;

            logger.debug("scaleImage width=" + width + " height=" + height);

            //首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。
            Graphics2D gs = (Graphics2D) originImage.getGraphics();


            gs.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            gs.setFont(new Font(FONT_FAMILY, Font.BOLD, 92));
            TemplateTheme theme = new TemplateTheme("#000000", "#ffffff");

            // fill bgColor
            gs.setColor(theme.getFrontColor());//2b96ac

            // fill head_image
            if (!isTemplate) {
                BufferedImage logourl = ImageUtil.getUrlByBufferedImage(RedisUtils.get(Constants.REDIS_USER_LOGO + uid));
                BufferedImage cirlebi = ImageUtil.convertCircular(ImageUtil.scaleByPercentage(logourl, 170, 170), false);
                gs.drawImage(cirlebi, 450, 864, null);
            }

            // fill text
            if (isTemplate) {
                int startX = 80;
                int startY = 350;
                String[] words = word.replace(",", "，").split("，");
                if (words.length == 1) startY = 380;
                java.util.List<LineWord> alllist = new ArrayList<LineWord>();
                for (String item : words) {
                    java.util.List<LineWord> list = getSpliteLineNoAutowrap(item, gs.getFontMetrics(), 840, false);
                    alllist.addAll(list);
                }

                for (LineWord item : alllist) {
                    gs.drawString(item.getWord(), 516 - item.getWidth() / 2, startY);
                    startY += 120;
                }
            }

            // 生成
            String filepath = null;
            File file = null;
            if (isTemplate) {
                filepath = Constants.WX_QBD_IMAGEPATH_PYQ + "zhufu" + order + ".png" ;
                file = new File(filepath);
            } else {
                filepath = Constants.WX_QBD_IMAGEPATH_PYQ + "zhufu_terminal" + order + ".png" ;
                file = new File(filepath);
            }


            ImageIO.write(originImage, "png", file);
            try {
                Runtime.getRuntime().exec("chmod 644 " + filepath);
            } catch (IOException e) {
                logger.error("chmod 644 " + filepath + " error", e);
            }

//            if(!isTemplate) {

            String mediaId = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_QIANBAIDU
                    , Constants.WEIXIN_MATERIAL_IMAGE
                    , uid, filepath, Constants.WX_EVT_WISDOM, 1);

            WeixinUtil.sendCustomMsg(uid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId,
                    Constants.WEIXIN_QIANBAIDU);

            RedisUtils.setList("yuanmeng_2018", mediaId);
            logger.debug(">>>mediaId=" + mediaId);
//            }

            logger.debug(">>>zhufu image over");

            return filepath;
//            file.delete();

        } catch (Exception e) {
            logger.error("error happen", e);
        }
        return "file error" ;
    }

    public static java.util.List<String> getSpliteLine(String content, FontMetrics metric, int lineWidth, boolean isEnglish) {
        if (Strings.isNullOrEmpty(content)) return null;

        java.util.List<String> list = new ArrayList<String>();
        char[] arrs = content.toCharArray();

        int maxLeftlength = isEnglish ? getMaxWordlength(content, metric) : metric.stringWidth(String.valueOf(arrs[0]))*3;

        int llength = 0;
        StringBuilder linepender = new StringBuilder();

        for (int i = 0; i < arrs.length; i++) {
            if (llength == 0 && Character.isSpace(arrs[i])) continue;

            linepender.append(arrs[i]);
            llength += metric.stringWidth(String.valueOf(arrs[i]));

            if (isEnglish && i + 1 < arrs.length && Character.isSpace(arrs[i + 1]) && lineWidth - llength < maxLeftlength) {
                list.add(linepender.toString());
                linepender = new StringBuilder();
                llength = 0;
            }
            if (!isEnglish && lineWidth - llength < maxLeftlength) {
                list.add(linepender.toString());
                linepender = new StringBuilder();
                llength = 0;
            }

        }
        if (linepender.toString().length() > 0) list.add(linepender.toString());

        return list;
    }

    public static java.util.List<LineWord> getSpliteLineNoAutowrap(String content, FontMetrics metric, int lineWidth, boolean isEnglish) {
        if (Strings.isNullOrEmpty(content)) return null;

        java.util.List<LineWord> list = new ArrayList<LineWord>();
        char[] arrs = content.toCharArray();
        int maxLeftlength = isEnglish ? getMaxWordlength(content, metric) : metric.stringWidth(String.valueOf(arrs[0]))*3;

        int llength = 0;
        StringBuilder linepender = new StringBuilder();
        LineWord word = null;

        for (int i = 0; i < arrs.length; i++) {
            if (word == null) word = new LineWord();

            if (llength == 0 && Character.isSpace(arrs[i])) continue;

            if (isEnglish && i + 1 < arrs.length && Character.isSpace(arrs[i + 1]) && lineWidth - llength < maxLeftlength) {
                word.setWidth(llength);
                word.setWord(linepender.toString());
                list.add(word);
                word = null;
                linepender = new StringBuilder();
                llength = 0;
                continue;
            }
            if (!isEnglish && lineWidth - llength < maxLeftlength) {
                word.setWidth(llength);
                word.setWord(linepender.toString());
                list.add(word);
                word = null;
                linepender = new StringBuilder();
                llength = 0;
                continue;
            }

            linepender.append(arrs[i]);
            llength += metric.stringWidth(String.valueOf(arrs[i]));
        }
        if (linepender.toString().length() > 0) {
            word.setWidth(llength);
            word.setWord(linepender.toString());
            list.add(word);
        }

        return list;
    }

    public static java.util.List<String> getSpliteLineBysymbol(String content, FontMetrics metric, int lineWidth, boolean isEnglish) {
        if (Strings.isNullOrEmpty(content)) return null;

        java.util.List<String> list = new ArrayList<String>();
        String[] arrs = content.split(RegexUtil.REGEX_TAIL_CHAR.pattern());

        int singleWordWidth = metric.stringWidth("你");
        int lastLen = -1;
        int lastIndex = -1;
        boolean isRepeat = false;
        for (int i = 0; i < arrs.length; i++) {
            if (arrs[i].length() * singleWordWidth > lineWidth) {
                list = null;
                break;
            }
            if (i > 0 && lastLen != -1 && !isRepeat && arrs[i].length() + lastLen <= 20) {
                list.set(lastIndex, list.get(lastIndex) + "，" + arrs[i]);
                lastLen = -1;
                isRepeat = true;
            } else {
                list.add(arrs[i]);
                lastLen = arrs[i].length();
                lastIndex++;
                isRepeat = false;
            }
        }
        return list;
    }

    private static int getMaxWordlength(String content, FontMetrics metric) {

        int len = 0;
        if (Strings.isNullOrEmpty(content)) return len;
        String[] arrs = content.split(" ");
        int index = 0;
        for (int i = 0; i < arrs.length; i++) {
            if (arrs[i].length() > len) {
                len = arrs[i].length();
                index = i;
            }
        }

        return metric.stringWidth(arrs[index]);
    }

    public static void graphicsGeneration() throws Exception {

        // 实际数据行数+标题+备注
        int totalrow = 6;
        int totalcol = 5;
        int imageWidth = 1024;
        int imageHeight = totalrow * 40 + 20;
        int rowheight = 40;
        int startHeight = 10;
        int startWidth = 10;
        int colwidth = ((imageWidth - 20) / totalcol);

        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();

        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(new Color(220, 240, 240));

        // 画横线
        for (int j = 0; j < totalrow - 1; j++) {
            graphics.setColor(Color.black);
            graphics.drawLine(startWidth, startHeight + (j + 1) * rowheight,
                    imageWidth - 5, startHeight + (j + 1) * rowheight);
        }
        // 末行
        graphics.setColor(Color.black);
        graphics.drawLine(startWidth, imageHeight - 90, imageWidth - 5,
                imageHeight - 90);

        // 画竖线
        for (int k = 0; k < totalcol; k++) {
            graphics.setColor(Color.black);
            graphics.drawLine(startWidth + k * colwidth, startHeight
                    + rowheight, startWidth + k * colwidth, imageHeight - 50);
        }
        // 末列
        graphics.setColor(Color.black);
        graphics.drawLine(imageWidth - 5, startHeight + rowheight,
                imageWidth - 5, imageHeight - 50);

        // 设置字体
        Font font = new Font("华文楷体", Font.BOLD, 20);
        graphics.setFont(font);

        // 写标题
        String title = "标题写在这里" ;
        graphics.drawString(title, imageWidth / 3 + startWidth, startHeight
                + rowheight - 10);

        font = new Font("华文楷体", Font.BOLD, 18);
        graphics.setFont(font);

        // 写入表头
        String[] headCells = {"编号", "名称", "年龄", "性别", "体重"};
        for (int m = 0; m < headCells.length; m++) {
            graphics.drawString(headCells[m].toString(), startWidth + colwidth
                    * m + 5, startHeight + rowheight * 2 - 10);
        }

        // 设置字体
        font = new Font("华文楷体", Font.PLAIN, 16);
        graphics.setFont(font);
        String[][] cellsValue = {{"101", "xiaozhang", "13", "M", "55"},
                {"102", "xiaowang", "14", "F", "53"},
                {"103", "同事接听，工作信息核实无误，收入纯打卡，无现金发薪同事接听，工作信息核实无误，收入纯打卡，无现金发薪同事接听，工作信息核实无误，收入纯打卡，无现金发薪同事接听，工作信息核实无误，收入纯打卡，无现金发薪", "15", "M", "58"}};
        // 写入内容
        for (int n = 0; n < cellsValue.length; n++) {
            String[] arr = cellsValue[n];
            for (int l = 0; l < arr.length; l++) {
                graphics.drawString(cellsValue[n][l].toString(), startWidth
                        + colwidth * l + 5, startHeight + rowheight * (n + 3)
                        - 10);
            }
        }

        font = new Font("华文楷体", Font.BOLD, 18);
        graphics.setFont(font);
        graphics.setColor(Color.RED);

        // 写备注
        String remark = "备注：备注写在这里。" ;
        graphics.drawString(remark, startWidth, imageHeight - 30);

        //createImage("D:\\1.jpg");

        ImageIO.write(image, "jpg", new File("/Users/chenxuebin/Downloads/tmp_txt/img/table.jpg"));

        // =========== start to write to servlet  ==============
//        g.drawImage(ImageIO.read(getServletContext().getResourceAsStream(t.getPicUrl())), null, 198, 61);
    }

    public static void yasuo(String path, Integer w1, Integer h1) {

        File image = new File(path);
        logger.info("------------file yasuo path=" + path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return;
        } else {
            logger.info("------------file exist for path=" + path);
        }
        if (path.toLowerCase().lastIndexOf(".png") > 0 ||
                path.toLowerCase().lastIndexOf(".jpg") > 0 ||
                path.toLowerCase().lastIndexOf(".jpeg") > 0) {
            logger.info("------------file is image" + path);
        } else {
            logger.info("------------file is not image");
            return;
        }

        try {
            BufferedImage originImage = ImageIO.read(new FileInputStream(path));
            int width = originImage.getWidth();
            int height = originImage.getHeight();

            if (width <= 750 && w1 == null) return;
            if (w1 != null && width <= w1) return;

            logger.info("------------originImage width=" + originImage.getWidth() + " height=" + originImage.getHeight());
            int wd1 = (w1 == null) ? 750 : w1;
            int hg1 = (h1 == null) ? wd1 * height / width : h1;
            logger.info("--------------------------w1="+w1);
            if (w1 == null){
                Thumbnails.of(path).size(wd1, hg1).toFile(path);
            }
            else {
                logger.info("------------w1 is not null height=" + height);
                logger.info("------------w1 is not null h1=" + h1);
                if (h1 != null && height <= h1) return;
                int i =1;
                while (wd1*i<width&&hg1*i< height){
                    i++;
                }
                Thumbnails.of(path).sourceRegion(Positions.CENTER, wd1*i, hg1*i).size(wd1, hg1)
                        .keepAspectRatio(true).toFile(path);
            }

        } catch (Exception e) {
            logger.error("");
        }
    }

    public static boolean checkimg(String path) {

        File image = new File(path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return false;
        }

        try {
            BufferedImage originImage = ImageIO.read(new FileInputStream(path));
            int width = originImage.getWidth();
            return width>0;
        } catch (Exception e) {
            logger.error("");
            return false;
        }
    }


}
